package com.zbl.zblproject.erp.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.zbl.zblproject.core.entity.AdminUser;
import com.zbl.zblproject.core.entity.Result;
import com.zbl.zblproject.core.mapper.AdminUserMapper;
import com.zbl.zblproject.core.utils.ResultUtil;
import com.zbl.zblproject.core.utils.StringUtil;
import com.zbl.zblproject.erp.entity.ErpInventoryOrder;
import com.zbl.zblproject.erp.entity.ErpInventoryOrderItem;
import com.zbl.zblproject.erp.service.ErpInventoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


/**
 * @author youlanqiang
 * @version 1.0
 * @date 2018/10/19
 */
@RestController
@RequestMapping("/erp-inventory")
@Api(tags = {"库存操作接口"})
public class ErpInventoryController {

    @Autowired
    private ErpInventoryService erpInventoryService;

    @Autowired
    private AdminUserMapper adminUserMapper;


    private static final Logger logger = LoggerFactory.getLogger(ErpInventoryOrder.class);


    @GetMapping("/get-context/{orderSn}")
    @ApiOperation("获取对应订单的订单备注")
    public Result getContext(@ApiParam("订单号") @PathVariable String orderSn){
        ErpInventoryOrder  order =  erpInventoryService.getOrderBySn(orderSn);
        if(order == null){
            return ResultUtil.error("没有对应订单");
        }
        return ResultUtil.success("成功", order.getContext());
    }

    @GetMapping("/update-context/{orderSn}")
    @ApiOperation("更新对应订单的订单备注")
    public Result getContext(@ApiParam("订单号") @PathVariable String orderSn,
                             @ApiParam("备注") @RequestParam("context") String context){
        if(erpInventoryService.updateOrderContext(orderSn, context)){
            return ResultUtil.success("更新成功");
        }
        return ResultUtil.error("更新失败");
    }


    @PostMapping("/rollback/{id}")
    @ApiOperation("回滚订单")
    public Result rollback(@ApiParam("客户ID") @RequestParam("userId") int userId,
                           @ApiParam("订单ID") @PathVariable int id){
        try {
            AdminUser user = getUserById(userId);
            if(erpInventoryService.rollback(id)) {
                return ResultUtil.success("成功!");
            }else{
                return ResultUtil.error("失败");
            }
        }catch(Exception e){
            e.printStackTrace();
            return ResultUtil.error(e.getMessage());
        }
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除订单")
    public Result deleteOrder(@ApiParam("删除订单") @PathVariable int id){
        if(erpInventoryService.deleteOrderById(id)){
            return ResultUtil.success("成功!");
        }else{
            return ResultUtil.error("失败!");
        }
    }

    @GetMapping("/inlist/{current}/{size}/{mode}")
    @ApiOperation("入库订单列表查询")
    public Result listByIn(@ApiParam("查询页数") @PathVariable int current,
                           @ApiParam("查询数量") @PathVariable int size,
                           @ApiParam("查询订单号") @RequestParam("search") String search,
                           @ApiParam("起始时间") @RequestParam("start") String start,
                           @ApiParam("结束时间") @RequestParam("end") String end,
                           @ApiParam("查询用户姓名") @RequestParam("user") String user,
                           @ApiParam("查询状态 -1 为查询全部") @RequestParam("status") int status,
                           @ApiParam("查询模式") @PathVariable int mode){
        String searchStr = searchStr(search, start, end, user, status, mode);
        return ResultUtil.success("成功", erpInventoryService.page(searchStr, current, size));
    }

    @GetMapping("/desc/{orderNo}")
    @ApiOperation("获取订单下的所有项")
    public Result descOrder(@ApiParam("订单号") @PathVariable String orderNo){
            try{
                List<ErpInventoryOrderItem> list =  erpInventoryService.orderItemByOrderSn(orderNo);
                return ResultUtil.success("成功!", list);
            }catch(Exception e){
                return ResultUtil.error(e.getMessage());
            }
    }

    @PostMapping("/update/{orderNo}")
    @ApiOperation("更新订单状态")
    public Result update(@ApiParam("订单号") @PathVariable String orderNo){

        try{
            boolean result =   erpInventoryService.updateOrder(orderNo);
            if(result){
                return ResultUtil.success("成功!");
            }else{
                return ResultUtil.error("失败");
            }
        }catch(Exception e){
            e.printStackTrace();
            return ResultUtil.error(e.getMessage());
        }
    }


    @PostMapping("/flushInventory/{orderNo}")
    @ApiOperation("盘点遗漏")
    public Result flushInventory(@ApiParam("订单号") @PathVariable String orderNo,
                                  @ApiParam("客户ID") @RequestParam("userId") int userId,
                                  @RequestParam("items") String items){
            try {
                AdminUser user =getUserById(userId);
              //  logger.info("json数据: {}", items);
                boolean result = erpInventoryService.flushOrder(orderNo, parseJson(items));
                if(result){
                    return ResultUtil.success("更新成功!");
                }else{
                    return ResultUtil.error("更新失败!");
                }
            }catch(Exception e){
                e.printStackTrace();
                return ResultUtil.error(e.getMessage());
            }
    }


    @PostMapping("/createInventory/{orderNo}/{status}")
    @ApiOperation("创建盘货订单")
    public Result createInventory(@ApiParam("订单号") @PathVariable String orderNo,
                                  @ApiParam("客户ID") @RequestParam("userId") int userId,
                                  @ApiParam("订单状态") @PathVariable int status,
                                  @RequestParam("items") String items){
        try {
            AdminUser user =getUserById(userId);
          //  logger.info("json数据: {}", items);
            ErpInventoryOrder order = erpInventoryService.createOrderByStatus(0, orderNo, "", status, user, parseJson(items));
            return ResultUtil.success("成功!", order);
        }catch(Exception e){
            e.printStackTrace();
            return ResultUtil.error(e.getMessage());
        }
    }

    @PostMapping("/createBreakage/{orderNo}/{status}")
    @ApiOperation("创建报损单")
    public Result createBreakage(@ApiParam("订单号") @PathVariable String orderNo,
                                 @ApiParam("客户ID") @RequestParam("userId") int userId,
                                 @ApiParam("订单状态") @PathVariable int status,
                                 @RequestParam("items") String items){
            try {
                AdminUser user = getUserById(userId);
              //  logger.info("json数据: {}", items);
                ErpInventoryOrder order = erpInventoryService.createOrderByStatus(1, orderNo, "", status, user, parseJsonSkipZero(items));
                return ResultUtil.success("成功!", order);
            }catch(Exception e){
                return ResultUtil.error(e.getMessage());
            }
    }

    @PostMapping("/createReceive/{orderNo}/{status}")
    @ApiOperation("创建领用单")
    public Result createReceive(@ApiParam("订单号") @PathVariable String orderNo,
                                 @ApiParam("客户ID") @RequestParam("userId") int userId,
                                 @ApiParam("订单状态") @PathVariable int status,
                                 @ApiParam("订单备注") @RequestParam("context") String context,
                                 @ApiParam("订单项") @RequestParam("items") String items){
        try {
            AdminUser user = getUserById(userId);
          //  logger.info("json数据: {}", items);
            ErpInventoryOrder order = erpInventoryService.createOrderByStatus(2, orderNo, context, status, user, parseJsonSkipZero(items));
            return ResultUtil.success("成功!", order);
        }catch(Exception e){
            return ResultUtil.error(e.getMessage());
        }
    }

    @PostMapping("/createReturn/{orderNo}/{status}")
    @ApiOperation("创建退货单")
    public Result createReturn(@ApiParam("订单号") @PathVariable String orderNo,
                                @ApiParam("客户ID") @RequestParam("userId") int userId,
                                @ApiParam("订单状态") @PathVariable int status,
                                @RequestParam("items") String items){
        try {
            AdminUser user = getUserById(userId);
        //    logger.info("json数据: {}", items);
            ErpInventoryOrder order = erpInventoryService.createOrderByStatus(3, orderNo, "", status, user, parseJsonSkipZero(items));
            return ResultUtil.success("成功!", order);
        }catch(Exception e){
            return ResultUtil.error(e.getMessage());
        }
    }

    private AdminUser getUserById(int userId){
        AdminUser user = adminUserMapper.selectById(userId);
        Preconditions.checkNotNull(user, "用户不存在!");
        if(user.getStatus() != 0){
            throw new RuntimeException("用户被封禁!");
        }
        return user;
    }


    private List<ErpInventoryOrderItem> parseJsonSkipZero(String json){
        List<ErpInventoryOrderItem> list = new ArrayList<>();
        JSONArray array = JSONArray.parseArray(json);
        JSONObject object;
        ErpInventoryOrderItem orderItem;
        for(int i = 0; i < array.size(); i++){
            object = array.getJSONObject(i);
            orderItem = new ErpInventoryOrderItem();
            orderItem.setWhId(object.getInteger("goodsList"));
            if(orderItem.getWhId() == 0){
                throw new RuntimeException("仓库位置未选择!");
            }
            orderItem.setGoodsId(object.getInteger("goodsId"));
            orderItem.setInventoryNum(object.getInteger("goodsNum"));
            orderItem.setInventoryPrice(object.getBigDecimal("goodsPrice"));
            if(orderItem.getInventoryNum() > 0){
                list.add(orderItem);
            }
        }
        return list;
    }

    private List<ErpInventoryOrderItem> parseJson(String json){

        List<ErpInventoryOrderItem> list = new ArrayList<>();

        JSONArray array = JSONArray.parseArray(json);
        JSONObject object;
        ErpInventoryOrderItem orderItem;
        for(int i = 0; i < array.size(); i++){
            object = array.getJSONObject(i);
            orderItem = new ErpInventoryOrderItem();
            orderItem.setWhId(object.getInteger("goodsList"));
            if(orderItem.getWhId() == 0){
                throw new RuntimeException("仓库位置未选择!");
            }
            orderItem.setGoodsId(object.getInteger("goodsId"));
            orderItem.setInventoryNum(object.getInteger("goodsNum"));
            orderItem.setInventoryPrice(object.getBigDecimal("goodsPrice"));
            list.add(orderItem);
        }
        return list;
    }


    private String searchStr(String search, String start, String end, String user, int status, int mode){
        StringBuilder buffer = new StringBuilder();
        buffer.append(" DATE_FORMAT(create_time, '%Y-%m-%d') >= ");
        buffer.append("'").append(start).append("'");
        buffer.append(" AND ");
        buffer.append(" DATE_FORMAT(create_time, '%Y-%m-%d') <= ");
        buffer.append("'").append(end).append("'");

        if(!Strings.isNullOrEmpty(search.trim())) {
            buffer.append(" AND");
            buffer.append(" inventory_sn LIKE '%");
            buffer.append(StringUtil.sql(search));
            buffer.append("%' ");
        }

        if(!Strings.isNullOrEmpty(user.trim())){
            buffer.append(" AND");
            buffer.append(" operator LIKE '%");
            buffer.append(StringUtil.sql(user));
            buffer.append("%' ");
        }

        if(status != -1){
            buffer.append(" AND");
            buffer.append(" status = ").append(status);
        }
        buffer.append(" AND");
        buffer.append(" mode = ").append(mode);

        logger.info("条件语句: "+buffer.toString());
        return buffer.toString();
    }




}
